package com.jilian.mydemo.modul.main.ui;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseFragment;
import com.jilian.mydemo.common.dto.BannerDto;
import com.jilian.mydemo.common.dto.BannerListDto;
import com.jilian.mydemo.common.dto.LeaveStatusDto;
import com.jilian.mydemo.common.vo.BannerVo;
import com.jilian.mydemo.common.vo.LeaveVo;
import com.jilian.mydemo.factory.Factoty;
import com.jilian.mydemo.listener.ViewPagerItemClickListener;
import com.jilian.mydemo.modul.exam.ui.CooperationThatActivity;
import com.jilian.mydemo.modul.exam.ui.HydraulicClassroomActivity;
import com.jilian.mydemo.modul.main.adapter.BananerPagerAdapter;
import com.jilian.mydemo.modul.order.ui.WebViewActivity;
import com.jilian.mydemo.modul.shop.ui.AccessoriesShopActivity;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.DateUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.RxTimerUtil;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.views.CornerView;
import com.jilian.mydemo.views.ViewPagerIndicator;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class OneFragment extends BaseFragment implements ViewPagerItemClickListener {

    private ViewPager viewPager;
    private LinearLayout llIndcator;
    private List<BannerDto> list;
    private BananerPagerAdapter bananerPagerAdapter;
    private CornerView cornerView;
    private TextView tvOk;
    private LinearLayout llOne;
    private LinearLayout llTwo;
    private LinearLayout llMsg;
    private UserViewModel userViewModel;






    @Override
    protected void loadData() {

    }


    @Override
    protected void createViewModel() {
        userViewModel = Factoty.getViewModel(UserViewModel.class,this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_one;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        tvOk = (TextView) view.findViewById(R.id.tv_ok);
        viewPager = (ViewPager)view. findViewById(R.id.viewPager);
        llIndcator = (LinearLayout) view.findViewById(R.id.ll_indcator);
        cornerView = (CornerView) view.findViewById(R.id.cornerView);
        llMsg = (LinearLayout) view.findViewById(R.id.ll_msg);
        llOne = (LinearLayout) view.findViewById(R.id.ll_one);
        llTwo = (LinearLayout) view.findViewById(R.id.ll_two);
        cornerView.setCorner(0);
    }

    /**
     * 初始化banner
     */
    private void initBanner() {
        viewPager.addOnPageChangeListener(new ViewPagerIndicator(getmActivity(), viewPager, llIndcator, list.size()));
        bananerPagerAdapter = new BananerPagerAdapter(getmActivity(),list,this);
        viewPager.setAdapter(bananerPagerAdapter);
    }

    @Override
    protected void initData() {
        initStatus();
        initCustomTimePicker();
        getBanner();
    }


    private int leaveStatus;// 请假状态，0：非请假状态，1：处在请假状态
    /**
     * 获取请假状态
     */

    private void initStatus() {

        userViewModel.getLeaveStatus();
        userViewModel.getLeaveStatusliveData().observe(this, new Observer<BaseDto<LeaveStatusDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<LeaveStatusDto> leaveStatusDtoBaseDto) {
                tvOk.setEnabled(true);
                hideLoadingDialog();
                if(leaveStatusDtoBaseDto.isSuccess()){
                    if(leaveStatusDtoBaseDto.getData()!=null){
                        //请假状态，0：非请假状态，1：处在请假状态
                        leaveStatus = leaveStatusDtoBaseDto.getData().getLeaveStatus();
                        if(leaveStatusDtoBaseDto.getData().getLeaveStatus()==0){
                            tvOk.setBackgroundResource(R.drawable.shape_main_white_6);
                            tvOk.setTextColor(getResources().getColor(R.color.color_main_title));
                            tvOk.setText("取消接单");
                            tvOk.setVisibility(View.VISIBLE);
                        }
                        else if(leaveStatusDtoBaseDto.getData().getLeaveStatus()==1){
                            tvOk.setBackgroundResource(R.drawable.shape_btn_login_normal);
                            tvOk.setTextColor(getResources().getColor(R.color.color_white));
                            tvOk.setText("开始接单");
                            tvOk.setVisibility(View.VISIBLE);
                        }
                    }
                    else{
                        ToastUitl.showImageToastTips(leaveStatusDtoBaseDto.getMsg());
                    }
                }
                else{
                    ToastUitl.showImageToastTips(leaveStatusDtoBaseDto.getMsg());
                }
            }
        });

    }

    @Override
    protected void initListener() {
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(leaveStatus == 1){
                    //接单
                    takeOrder();
                }
                else{
                    //请假
                    selectDay();
                }
            }
        });
        //配件商城
        llOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(),AccessoriesShopActivity.class));
            }
        });
        //水工课堂
        llTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(),HydraulicClassroomActivity.class));

            }
        });

        llMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(),CooperationThatActivity.class));
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 选择生日
     */
    private void selectDay() {

        pvCustomTime.show(); //弹出自定义时间选择器


    }
    TimePickerView pvCustomTime;
    /**
     * 初始化时间数据
     */
    private void initCustomTimePicker() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
       // Calendar selectedDate = Calendar.getInstance();//系统当前时间

        Calendar startDate = Calendar.getInstance();
        startDate.set(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH),  startDate.get(Calendar.DAY_OF_MONTH)+1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(endDate.get(Calendar.YEAR), 12,  31);

        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(getmActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String str = DateUtil.dateToString(DateUtil.DATE_FORMAT_, date)+" 23:59:59";
                //去请假
                askForLeave(str);
            }
        })
                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentTextSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               /*.setDividerColor(Color.WHITE)//设置分割线的颜色
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)*/
                /*.animGravity(Gravity.RIGHT)// default is center*/
                .setDate(startDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(40, 0, -40, 0, 0, -0)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFFe0e0e0)
                .setLineSpacingMultiplier(2f)
                .build();
    }

    /**
     * 接单
     */
        private void takeOrder() {
        tvOk.setEnabled(false);
        showLoadingDialog();
        userViewModel.takeOrder();
        userViewModel.getTakeOrderLiveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if(dto.isSuccess()){
                    ToastUitl.showImageToastTips("操作成功");
                    initStatus();

                }
                else{
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }
    /**
     * 请假
     * @param str
     */
    private void askForLeave(String str) {
        tvOk.setEnabled(false);
        showLoadingDialog();
        LeaveVo vo = new LeaveVo();
        vo.setLeaveTime(str);
        userViewModel.leave(vo);
        userViewModel.getLeaveliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if(dto.isSuccess()){
                    ToastUitl.showImageToastTips("操作成功");
                    initStatus();

                }
                else{

                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    /**
     * 获取广告banner
     */
    private void getBanner() {
        BannerVo vo = new BannerVo();
        vo.setLocation(1);
        userViewModel.getAppAdList(vo);
        userViewModel.getBannerLiveData().observe(this, new Observer<BaseDto<BannerListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<BannerListDto> dto) {
                if(dto.isSuccess()&&dto.getData()!=null&&EmptyUtils.isNotEmpty(dto.getData().getList())){
                    list = new ArrayList<>();
                    list.addAll(dto.getData().getList());
                    initBanner();
                    startTimeTaskForBanner();
                }
            }
        });
    }
    private int mPosition = 0;

    /**
     * 开启轮播
     */
    private void startTimeTaskForBanner() {
        if (bananerPagerAdapter != null && bananerPagerAdapter.getCount() > 1) {
            mPosition = 0;
            RxTimerUtil.cancel();
            RxTimerUtil.interval(4000, new RxTimerUtil.IRxNext() {
                @Override
                public void doNext() {
                    mPosition++;
                    if (mPosition == bananerPagerAdapter.getCount()) {
                        mPosition = 0;
                    }
                    viewPager.setCurrentItem(mPosition);
                }
            });
        }
    }

    @Override
    public void onViewPageItemClick(View view, int position) {
        String url = list.get(position).getAdUrl();
        if(TextUtils.isEmpty(url)){
            return;
        }
        Intent intent = new Intent(getActivity(),WebViewActivity.class);
        intent.putExtra("linkUrl",url);
        startActivity(intent);

    }

}
